package com.h3c.web.interceptor;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.h3c.dal.common.TableConstant;
import com.h3c.dal.dao.CasssoUserDAO;
import com.h3c.dal.dao.CasssoUserRoleRelationDAO;
import com.h3c.dal.entity.CasssoUserDO;
import com.h3c.dal.entity.CasssoUserRoleRelationDO;
import com.h3c.dal.entity.query.CasssoUserQuery;
import com.h3c.dal.entity.query.CasssoUserRoleRelationQuery;
import com.h3c.web.common.constant.SessionConstant;
import com.h3c.web.common.constant.UrlConstant;
import com.h3c.web.common.helper.UserHelper;
import com.h3c.web.common.utils.ListUtil;
import com.h3c.web.common.utils.SpringContextUtil;

/**
 * @ClassName: LoginAuthInterceptor
 * @Description: 登录授权
 * @author: d14287
 * @date: 2017年5月20日 下午4:55:53
 */
public class LoginAuthInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private CasssoUserDAO casssoUserDAO;
	@Autowired
	private CasssoUserRoleRelationDAO casssoUserRoleRelationDAO;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator = (CookieRetrievingCookieGenerator) SpringContextUtil
				.getBean("ticketGrantingTicketCookieGenerator");
		TicketRegistry ticketRegistry = (TicketRegistry) SpringContextUtil.getBean("ticketRegistry");
		String serviceTicketId = ticketGrantingTicketCookieGenerator.retrieveCookieValue(request);
		if (StringUtils.hasText(serviceTicketId)) {
			TicketGrantingTicket serviceTicket = (TicketGrantingTicket) ticketRegistry.getTicket(serviceTicketId);
			if (serviceTicket != null && serviceTicket.isExpired() == false) {
				String loginId = serviceTicket.getAuthentication().getPrincipal().getId();
				UserHelper.userThreadLocal.set(loginId);
				assembleSession(loginId, request);
				return true;
			}
		}
		response.sendRedirect(UrlConstant.CAS_LOGIN);
		return false;
	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
		UserHelper.userThreadLocal.remove();
	}
	@SuppressWarnings("unchecked")
	private void assembleSession(String loginId, HttpServletRequest request) throws SQLException {
		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute(SessionConstant.USER_ID);
		if (StringUtils.isEmpty(session.getAttribute(SessionConstant.USER_ID))) {
			CasssoUserQuery userExample = new CasssoUserQuery();
			userExample.createCriteria().andLoginIdEqualTo(loginId)
					.andStatusEqualTo(TableConstant.USER_STATUS_ACTIVATED);
			List<CasssoUserDO> userList = casssoUserDAO.selectByExample(userExample);
			if (ListUtil.isNotEmpty(userList)) {
				userId = userList.get(0).getUserId();
				session.setAttribute(SessionConstant.USER_ID, userList.get(0).getUserId());
				session.setAttribute(SessionConstant.OU_ID, userList.get(0).getOuId());
			}
		}
		if (StringUtils.isEmpty(session.getAttribute(SessionConstant.ROLE_ID))) {
			CasssoUserRoleRelationQuery userRoleExample = new CasssoUserRoleRelationQuery();
			userRoleExample.createCriteria().andUserIdEqualTo(userId)
					.andStatusEqualTo(TableConstant.COMMON_STATUS_NORMAL);
			List<CasssoUserRoleRelationDO> casssoUserRoleRelationDOList = casssoUserRoleRelationDAO
					.selectByExample(userRoleExample);
			if (casssoUserRoleRelationDOList != null && !casssoUserRoleRelationDOList.isEmpty()) {
				session.setAttribute(SessionConstant.ROLE_ID, casssoUserRoleRelationDOList.get(0).getRoleId());
			}
		}
	}
}
